/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/');
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value];
    }
    return value.toString().padStart(2, '0');
  });
  return time_str;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return '刚刚';
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前';
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前';
  } else if (diff < 3600 * 24 * 2) {
    return '1天前';
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分';
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ');
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split('&');
  searchArr.forEach((v) => {
    const index = v.indexOf('=');
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

/**
 * 拖拽移动
 * @param  {elementObjct} bar 鼠标点击控制拖拽的元素
 * @param {elementObjct}  target 移动的元素
 * @param {function}  callback 移动后的回调
 */
export function startDrag(bar, target, callback) {
  var params = {
    top: 0,
    left: 0,
    currentX: 0,
    currentY: 0,
    flag: false,
    cWidth: 0,
    cHeight: 0,
    tWidth: 0,
    tHeight: 0
  };

  // 给拖动块添加样式
  bar.style.cursor = 'move';

  // 获取相关CSS属性
  // o是移动对象
  // var getCss = function (o, key) {
  //   return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, false)[key];
  // };

  bar.onmousedown = function (event) {
    // 按下时初始化params
    var e = event ? event : window.event;
    params = {
      top: target.offsetTop,
      left: target.offsetLeft,
      currentX: e.clientX,
      currentY: e.clientY,
      flag: true,
      cWidth: document.body.clientWidth,
      cHeight: document.body.clientHeight,
      tWidth: target.offsetWidth,
      tHeight: target.offsetHeight
    };

    // 给被拖动块初始化样式
    target.style.margin = 0;
    target.style.top = params.top + 'px';
    target.style.left = params.left + 'px';

    if (!event) {
      // 防止IE文字选中
      bar.onselectstart = function () {
        return false;
      };
    }

    document.onmousemove = function (event) {
      // 防止文字选中
      window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();

      var e = event ? event : window.event;
      if (params.flag) {
        var nowX = e.clientX;
        var nowY = e.clientY;
        // 差异距离
        var disX = nowX - params.currentX;
        var disY = nowY - params.currentY;
        // 最终移动位置
        var zLeft = 0;
        var zTop = 0;

        zLeft = parseInt(params.left) + disX;
        // 限制X轴范围
        if (zLeft <= -parseInt(params.tWidth / 2)) {
          zLeft = -parseInt(params.tWidth / 2);
        }
        if (zLeft >= params.cWidth - parseInt(params.tWidth * 0.5)) {
          zLeft = params.cWidth - parseInt(params.tWidth * 0.5);
        }

        zTop = parseInt(params.top) + disY;
        // 限制Y轴范围
        if (zTop <= 0) {
          zTop = 0;
        }
        if (zTop >= params.cHeight - parseInt(params.tHeight * 0.5)) {
          zTop = params.cHeight - parseInt(params.tHeight * 0.5);
        }

        // 执行移动
        target.style.left = zLeft + 'px';
        target.style.top = zTop + 'px';
      }

      if (typeof callback == 'function') {
        callback(zLeft, zTop);
      }
    };

    document.onmouseup = function () {
      params.flag = false;
      document.onmousemove = null;
      document.onmouseup = null;
    };
  };
}
